#include "zhongzhibean.h"

void ZhongZhiBean::createObject(QJsonObject &obj, ZhongZhiBean *zhongzhi)
{
    obj.insert("num", zhongzhi->num);
    obj.insert("crop", zhongzhi->crop);
    obj.insert("type", zhongzhi->type);
}

ZhongZhiBean::ZhongZhiBean()
{

}

ZhongZhiBean::ZhongZhiBean(int num, QString crop,QString type)
{
    this->num = num;
    this->crop = crop;
    this->type = type;
}

QList<ZhongZhiBean> ZhongZhiBean::jsonToArray(QByteArray jsonArrayStr)
{
    QJsonParseError jsonError;
    QList<ZhongZhiBean> zhongzhis;
    const QJsonDocument &document = QJsonDocument::fromJson(jsonArrayStr, &jsonError);
    if(document.isNull() || jsonError.error != QJsonParseError::NoError) return zhongzhis;
    QJsonArray jsonArray = document.array(); //文档转化为Json对象
    for(int i = 0 ; i < jsonArray.size() ; i++){
        QJsonObject obj = jsonArray.at(i).toObject();
        int num = obj.value("num").toInt();
        QString crop = obj.value("crop").toString();
        QString type = obj.value("type").toString();
        zhongzhis.append(ZhongZhiBean(num, crop, type));
    }
    return zhongzhis;
}

QByteArray ZhongZhiBean::ArraytoJson(QList<ZhongZhiBean *> *zhongzhiBeans)
{
    QJsonDocument doc;
    QJsonArray array;
    if(zhongzhiBeans->isEmpty()) return "";
    for(int i = 0; i< zhongzhiBeans->size(); i++){
        QJsonObject obj;
        ZhongZhiBean *runshopBean = zhongzhiBeans->at(i);
        createObject(obj, runshopBean);
        array.append(obj);
    }
    doc.setArray(array);
    return doc.toJson();
}
